<?php
    require_once ("Includes/session.php");
    require_once ("Includes/simplecms-config.php"); 
    require_once ("Includes/connectDB.php");
    require_once("conf.php");  

    include("Includes/header.php"); 
    confirm_is_admin();

    //generate random password
    function get_random_string()
    {
        $random_string = "";
        $valid_chars="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_()*abcdefghijklmnopqrstuvwxyz";
        $num_valid_chars = strlen($valid_chars);
        for ($i = 0; $i < 9; $i++)
        {
            // pick a random number from 1 up to the number of valid chars
            $random_pick = mt_rand(1, $num_valid_chars);
            // take the random character out of the string of valid chars
            // subtract 1 from $random_pick because strings are indexed starting at 0, and we started picking at 1
            $random_char = $valid_chars[$random_pick-1];
            // add the randomly-chosen char onto the end of our string so far
            $random_string .= $random_char;
        }

        // return our finished random string
        return $random_string;
    }

    $val = trim($_SERVER['QUERY_STRING']);
    if (isset($_POST['Add']))
    {
        //check if the user name and password are valid
        $UserN = trim($_POST ['Username']);
        $PassW = trim($_POST['PW']);
        $CPassW = trim($_POST['CPW']);

        if(empty($UserN) || empty($PassW))
        {

            echo "<script type='text/javascript'>alert('Invalid User Name or Password!')</script>";

        }
        elseif(strcasecmp($PassW,$CPassW))
        {
            echo "<script type='text/javascript'>alert('Passwords not identical!')</script>";
        }
        else
        {
                //check if the user name is used
            $query = "SELECT * FROM users WHERE username = ? LIMIT 1";

            $check_name = $databaseConnection->prepare($query);
            $check_name->bind_param('s', $UserN);

            $check_name->execute();
            $check_name->store_result();

            if ($check_name->num_rows == 1)
            {
                echo "<script type='text/javascript'>alert('A user with same name already exists!')</script>";
            }
            else
            {

                //add user
                $query1 = "INSERT INTO users (username, password) VALUES (?, SHA(?))";

                $statement = $databaseConnection->prepare($query1);
                $statement->bind_param('ss', $UserN, $PassW);
                $statement->execute();
                $statement->store_result();


                $creationWasSuccessful = $statement->affected_rows == 1 ? true : false;
                if ($creationWasSuccessful)
                {
                    $userId = $statement->insert_id;

                    $addToUserRoleQuery = "INSERT INTO users_in_roles (user_id, role_id) VALUES (?, ?)";
                    $addUserToUserRoleStatement = $databaseConnection->prepare($addToUserRoleQuery);

                    $userRoleId = 2;
                    $addUserToUserRoleStatement->bind_param('dd', $userId, $userRoleId);
                    $addUserToUserRoleStatement->execute();
                    $addUserToUserRoleStatement->close();

                    echo "<script type='text/javascript'>alert('Student Added successfully!')</script>";


                }
                else
                {
                    echo "<script type='text/javascript'>alert('Failed registration')</script>";
                }
            }
    
        }
    }

        //edit

    elseif(!empty($val))
    {
        $vals = explode('=',$val);
        $UserN = $vals[1];
        if(empty($UserN))
        {
            echo "<script type='text/javascript'>alert('Invalid User Name!')</script>";
        }
        else
        {
            //check if the user name exists
            $query = "SELECT id FROM users WHERE username = ? LIMIT 1";

            $check_name = $databaseConnection->prepare($query);
            $check_name->bind_param('s', $UserN);

            $check_name->execute();
            $check_name->store_result();

            if($check_name->error)
            {
                echo "<script type='text/javascript'>alert('Database query failed!')</script>";
            }
            elseif ($check_name->num_rows == 1)
            {
                $temp;   
                $check_name->bind_result($temp);
                $check_name->fetch();

                $check_role = $databaseConnection->prepare("SELECT * FROM users_in_roles where user_id = ? and role_id=2 ");
                $check_role->bind_param('d', $temp);

                $check_role->execute();
                $check_role->store_result();

                if($check_role->error)
                {
                    echo "<script type='text/javascript'>alert('Database query failed!')</script>";
                }

                elseif ($check_role->num_rows != 1 )
                {
                    echo "<script type='text/javascript'>alert('You can\'t edit an admin!!')</script>";
                }
                else
                {           
                    echo "<h2>".$UserN."</h2><br/>";
                    echo "<div id=''>\n<form action=Manage_Student.php method='post'> <fieldset>";
                    echo "student info goes here<br/><br/>";
                    echo "<input type=\"hidden\" name=\"UN\" value=\"$temp\">";
                    echo "<input type=\"submit\" name=\"Delete\" value=\"Delete User\" id=\"dlt\" />";
                    echo "<input type=\"submit\" name=\"ResetP\" value=\"Reset Password\" id=\"rst\" />\n</fieldset>\n</form>";
                    echo"<p>\n<a href=\"index.php\">Cancel</a>\n</p>\n</div>";
                    $check_role->close();
                    exit;
                }
            }

            else
            {
                echo "<script type='text/javascript'>alert('No user with this name exists!')</script>";
            }
        }

        
    }
    //Delete User
    elseif(isset($_POST['Delete']))
    {
        //check not admin

        if(!isset($_POST["UN"]))
        {
            echo "<script type='text/javascript'>alert('Error!')</script>";
        }
        else
        {

            $UN = $_POST["UN"];
            $check_role = $databaseConnection->prepare("SELECT * FROM users_in_roles where user_id = ? and role_id=2 ");
            $check_role->bind_param('d', $UN);
            $check_role->execute();
            $check_role->store_result();

            if($check_role->error)
            {
                echo "<script type='text/javascript'>alert('Database query failed!')</script>";
            }

            elseif ($check_role->num_rows != 1 )
            {
                echo "<script type='text/javascript'>alert('You can\'t delete an admin!!')</script>";
            }

            else
            {
                $check_role -> close();
                //delete
                $query = "DELETE FROM users WHERE id = ? LIMIT 1";
                $statement = $databaseConnection->prepare($query);
                $statement->bind_param('s', $UN);
                $statement->execute();
                $statement->store_result();
            
                if ($statement->error)
                {
                    echo "<script type='text/javascript'>alert('Delete Failed!')</script>";
                }

                elseif ($statement->affected_rows == 1)
                {
                    echo "<script type='text/javascript'>alert('Delete action complete!')</script>";
                }
                else
                {
                    echo "<script type='text/javascript'>alert('Delete action failed!!')</script>";
                }

                $statement->close();
            }
        }
    }

    //Reset Password
    elseif(isset($_POST['ResetP']))
    {
        //check admin
        if(!isset($_POST["UN"]))
        {
            echo "<script type='text/javascript'>alert('Error!')</script>";

        }
        else
        {
            $UN = $_POST["UN"];
            $check_role = $databaseConnection->prepare("SELECT * FROM users_in_roles where user_id = ? and role_id=2 ");
            $check_role->bind_param('d', $UN);
            $check_role->execute();
            $check_role->store_result();

            if($check_role->error)
            {
                echo "<script type='text/javascript'>alert('Database query failed!')</script>";

            }

            elseif ($check_role->num_rows != 1 )
            {
                echo "<script type='text/javascript'>alert('You can\'t edit an admin!!')</script>";

            }

            else
            {
                $check_role -> close();
                //generate password
                $Pass = get_random_string();
        
                //set password
                $query = "UPDATE users SET password=SHA(?) WHERE id=? LIMIT 1";
                $statement = $databaseConnection->prepare($query);
                $statement->bind_param('sd',$Pass ,$UN);
                $statement->execute();
                $statement->store_result();

                if ($statement->error)
                {
                    echo "<script type='text/javascript'>alert('Reset Failed!')</script>";

                }

                elseif ($statement->affected_rows == 1)
                {
                    echo '<p>New Password:'.$Pass.'</p>';
                    echo' <p><a href="AccountSettings.php">Back</a></p>';
                    exit;

                }
                else
                {
                    echo "<script type='text/javascript'>alert('Reset action failed!!')</script>";
                }


                $statement->close();
            }
        }
    }

    
?>    
<div id="add">
    <h2>Add Student</h2>
        <form action="Manage_Student.php" method="post">
            <fieldset>
            <legend>Add Student</legend>
            <ol>
                <li>
                    <label for="Username">Username:</label> 
                    <input type="text" name="Username" value="" id="Username" required="" />
                </li>
                <li>
                    <label for="PW">Password:</label>
                    <input type="password" name="PW" id="PW" required="" onchange="validatePass(this,document.getElementById('CPW'));"/>
                </li>
                <li>
                    <label for="CPW">Confirm Password:</label>
                    <input type="password" name="CPW" id="CPW" required="" onchange="validatePass(document.getElementById('PW'),this);"/>
                </li>
            </ol>
            <input type="submit" name="Add" value="Add" />
            <p>
                <a href="index.php">Cancel</a>
            </p>
        </fieldset>
    </form>
    
</div>

<div id="edit">
        <h2>Edit Student</h2>
        <?php
            $dg = new C_DataGrid("SELECT username FROM users INNER JOIN users_in_roles ON users.id=users_in_roles.user_id","username", "exams");
            $dg -> set_query_filter("users_in_roles.role_id = 2");
            $dg -> set_dimension(400, 300); 
             
            $onSelectRow = <<<ONSELECTROW
            function(status, rowid)
            {
	            window.location = "Manage_Student.php?id="+rowid;
            }
ONSELECTROW;


                //$dg->add_event("jqGridSelectRow", $onSelectRow);
                $dg -> add_event("jqGridDblClickRow", $onSelectRow);
                $dg -> display();
        ?>

</div>
</div> <!-- End of outer-wrapper which opens in header.php -->

<?php include ("Includes/footer.php"); ?>